package com.love.marriage.userMembershipInfo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.love.marriage.common.enums.DefaultAmountTypeEnum;
import com.love.marriage.defaultAmountConfig.service.DefaultAmountConfigService;
import com.love.marriage.defaultAmountConfig.vo.DefaultAmountConfigVo;
import com.love.marriage.userChatInfo.service.UserChatInfoService;
import com.love.marriage.userChatInfo.vo.UserChatInfoVo;
import com.love.marriage.userInfo.mapper.UserInfoMapper;
import com.love.marriage.userInfo.vo.MemberAboutVo;
import com.love.marriage.userMembershipInfo.service.UserMemberPrivilegeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
@Slf4j
public class UserMemberPrivilegeServiceImpl implements UserMemberPrivilegeService {

    private final DefaultAmountConfigService defaultAmountConfigService;

    private final UserChatInfoService userChatInfoService;

    private final UserInfoMapper userInfoMapper;

    @Override
    public boolean addMemberPrivilege(Long userId) {
        // 查找会员信息
        List<MemberAboutVo> userMemberInfoList = userInfoMapper.getMemberAboutList(userId);
        log.info("查询当前会员数量：{}", userMemberInfoList.size());
        if (userMemberInfoList.isEmpty()) {
            return true;
        }
        List<String> codes = Lists.newArrayList("getPhone_num",
                "matchmaker_getPhone_num",
                "first_partner_getPhone_num",
                "second_partner_getPhone_num",
                "third_partner_getPhone_num");
        List<DefaultAmountConfigVo> phoneNumConfigInfo = defaultAmountConfigService.queryDefaultAmountConfigByCodes(codes);
        Map<String, DefaultAmountConfigVo> codeMap = phoneNumConfigInfo.parallelStream().collect(Collectors.toMap(DefaultAmountConfigVo::getConfigCode, a -> a, (oldVal, newVal) -> newVal));
        for (MemberAboutVo memberAboutVo : userMemberInfoList) {
            log.info("会员信息:{}", JSONObject.toJSONString(memberAboutVo));
            // 更新每日默认聊天数量
//            log.info("更新用户每日聊天数量，开始====================");
//            if (memberAboutVo.getMembershipFlag() != null && memberAboutVo.getMembershipFlag()) {
//                try {
//                    DefaultAmountConfigVo chatNumConfigInfo = defaultAmountConfigService.queryDefaultAmountConfigByCode(DefaultAmountTypeEnum.CHAT_COUNT.getCode());
//                    UserChatInfoVo chatNumInfo = new UserChatInfoVo();
//                    chatNumInfo.setUserId(memberAboutVo.getId());
//                    chatNumInfo.setChatCount(1000000);
//                    chatNumInfo.setType(DefaultAmountTypeEnum.CHAT_COUNT.getCode());
//                    userChatInfoService.addInfo(chatNumInfo);
//                } catch (Exception e) {
//                    log.error("更新用户每日聊天数量，失败====================:{}", e.getMessage());
//                }
//                log.info("更新用户每日聊天数量，结束====================");
//            }
            // 更新每日默认获取电话数量
            log.info("更新用户每日获取电话数量，开始====================");
            int phoneNum = 0;
            if (memberAboutVo.getMembershipFlag() != null && memberAboutVo.getMembershipFlag()) {
                phoneNum = Math.max(phoneNum, codeMap.get("getPhone_num").getAmount().intValue());
            }
            if (memberAboutVo.getMatchmakerFlag() != null && memberAboutVo.getMatchmakerFlag()) {
                phoneNum = Math.max(phoneNum, codeMap.get("matchmaker_getPhone_num").getAmount().intValue());
            }
            // 只有单身的合伙人才会获取收益
            if (memberAboutVo.getPartnerFlag() != null && memberAboutVo.getPartnerFlag() &&
                    memberAboutVo.getOfflineServiceProviderVo() != null &&
                    memberAboutVo.getOfflineServiceProviderVo().getSingleFlag() != null &&
                    memberAboutVo.getOfflineServiceProviderVo().getSingleFlag()) {
                switch (memberAboutVo.getPartnerType()) {
                    case "first":
                        phoneNum = Math.max(phoneNum, codeMap.get("first_partner_getPhone_num").getAmount().intValue());
                        break;
                    case "second":
                        phoneNum = Math.max(phoneNum, codeMap.get("second_partner_getPhone_num").getAmount().intValue());
                        break;
                    case "third":
                        phoneNum = Math.max(phoneNum, codeMap.get("third_partner_getPhone_num").getAmount().intValue());
                        break;
                    default:
                        break;
                }
            }
            try {
                UserChatInfoVo phoneNumInfo = new UserChatInfoVo();
                phoneNumInfo.setUserId(memberAboutVo.getId());
                phoneNumInfo.setChatCount(phoneNum);
                phoneNumInfo.setType(DefaultAmountTypeEnum.GET_PHONE_NUM.getCode());
                userChatInfoService.addInfo(phoneNumInfo);
            } catch (Exception e) {
                log.error("更新用户每日获取电话数量，失败====================:{}", e.getMessage());
                return false;
            }
            log.info("更新用户每日获取电话数量，结束====================");
            if (memberAboutVo.getMembershipFlag() != null &&
                    memberAboutVo.getMembershipFlag() &&
                    isWelfareGrantDay(memberAboutVo.getStartTime(), LocalDate.now())) {
                log.info("更新用户月会员权益，开始====================");
                try {
                    DefaultAmountConfigVo callNum = defaultAmountConfigService.queryDefaultAmountConfigByCode(DefaultAmountTypeEnum.CALL_NUM.getCode());
                    UserChatInfoVo phoneNumInfo = new UserChatInfoVo();
                    phoneNumInfo.setUserId(memberAboutVo.getId());
                    phoneNumInfo.setChatCount(callNum.getAmount().intValue());
                    phoneNumInfo.setType(DefaultAmountTypeEnum.CALL_NUM.getCode());
                    userChatInfoService.addInfo(phoneNumInfo);
                } catch (Exception e) {
                    log.error("更新用户月会员权益，失败====================:{}", e.getMessage());
                    return false;
                }
                log.info("更新用户月会员权益，结束====================");
            }
        }
        return true;
    }

    /**
     * @param memberStartDateTime
     * @param currentDate
     * @description: 判断当前日期是否到达用户把你会员的日期
     * @author: alex
     * @return: boolean
     */
    public boolean isWelfareGrantDay(LocalDateTime memberStartDateTime, LocalDate currentDate) {
        if (memberStartDateTime == null) {
            return false;
        }
        // 获取会员注册日期
        LocalDate memberStartDate = memberStartDateTime.toLocalDate();
        while (memberStartDate.isBefore(currentDate)) {
            memberStartDate = memberStartDate.plusMonths(1); // 每次加一个月
        }
        // 判断当前日期是否是福利发放日
        return memberStartDate.equals(currentDate);
    }
}
